import { Order, Statistics } from '../types';

export type WebSocketEventType = 
  | 'order_created'
  | 'order_updated'
  | 'order_assigned'
  | 'order_completed'
  | 'statistics_updated';

export interface WebSocketEvent {
  type: WebSocketEventType;
  data: any;
}

export interface WebSocketCallbacks {
  onOrderCreated?: (order: Order) => void;
  onOrderUpdated?: (order: Order) => void;
  onOrderAssigned?: (order: Order) => void;
  onOrderCompleted?: (order: Order) => void;
  onStatisticsUpdated?: (statistics: Statistics) => void;
  onConnect?: () => void;
  onDisconnect?: () => void;
  onError?: (error: Event) => void;
}

class WebSocketService {
  private ws: WebSocket | null = null;
  private callbacks: WebSocketCallbacks = {};
  private reconnectAttempts = 0;
  private maxReconnectAttempts = 5;
  private reconnectInterval = 3000;
  private isConnecting = false;
  private token: string | null = null;

  constructor() {
    this.token = localStorage.getItem('admin_token');
  }

  // 连接WebSocket
  connect(callbacks: WebSocketCallbacks = {}) {
    if (this.isConnecting || (this.ws && this.ws.readyState === WebSocket.OPEN)) {
      return;
    }

    this.callbacks = callbacks;
    this.isConnecting = true;

    try {
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      const wsUrl = `${protocol}//${window.location.host}/ws`;
      
      this.ws = new WebSocket(wsUrl);
      this.setupEventListeners();
    } catch (error) {
      console.error('WebSocket connection error:', error);
      this.isConnecting = false;
      this.callbacks.onError?.(error as Event);
    }
  }

  // 设置事件监听器
  private setupEventListeners() {
    if (!this.ws) return;

    this.ws.onopen = () => {
      console.log('WebSocket connected');
      this.isConnecting = false;
      this.reconnectAttempts = 0;
      
      // 发送认证信息
      if (this.token) {
        this.send({
          type: 'auth',
          token: this.token,
        });
      }
      
      this.callbacks.onConnect?.();
    };

    this.ws.onmessage = (event) => {
      try {
        const message: WebSocketEvent = JSON.parse(event.data);
        this.handleMessage(message);
      } catch (error) {
        console.error('Failed to parse WebSocket message:', error);
      }
    };

    this.ws.onclose = () => {
      console.log('WebSocket disconnected');
      this.isConnecting = false;
      this.callbacks.onDisconnect?.();
      this.handleReconnect();
    };

    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error);
      this.callbacks.onError?.(error);
    };
  }

  // 处理消息
  private handleMessage(message: WebSocketEvent) {
    switch (message.type) {
      case 'order_created':
        this.callbacks.onOrderCreated?.(message.data);
        break;
      case 'order_updated':
        this.callbacks.onOrderUpdated?.(message.data);
        break;
      case 'order_assigned':
        this.callbacks.onOrderAssigned?.(message.data);
        break;
      case 'order_completed':
        this.callbacks.onOrderCompleted?.(message.data);
        break;
      case 'statistics_updated':
        this.callbacks.onStatisticsUpdated?.(message.data);
        break;
      default:
        console.warn('Unknown WebSocket message type:', message.type);
    }
  }

  // 发送消息
  private send(data: any) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data));
    }
  }

  // 处理重连
  private handleReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
      
      setTimeout(() => {
        this.connect(this.callbacks);
      }, this.reconnectInterval);
    } else {
      console.error('Max reconnection attempts reached');
    }
  }

  // 断开连接
  disconnect() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
    this.isConnecting = false;
    this.reconnectAttempts = 0;
  }

  // 更新token
  updateToken(token: string | null) {
    this.token = token;
    if (this.ws && this.ws.readyState === WebSocket.OPEN && token) {
      this.send({
        type: 'auth',
        token: token,
      });
    }
  }

  // 获取连接状态
  getConnectionState(): number {
    return this.ws?.readyState ?? WebSocket.CLOSED;
  }

  // 是否已连接
  isConnected(): boolean {
    return this.ws?.readyState === WebSocket.OPEN;
  }
}

export const webSocketService = new WebSocketService();
export default webSocketService;